package com.texthtml;


import java.util.HashMap;
import java.util.LinkedList;

import com.alibaba.fastjson.JSON;


public class FastJson {

	/**
	 * 把Object转化为json String.   例如把HashMap转化为json String
	 * @param object  等转化的对象
	 * @return   Json String
	 * @see 例如把HashMap转化为json string
	 *      String str_json = object2JsonString(hm);
	 */
	public static String object2JsonString(Object obj) {   
		return  JSON.toJSONString(obj);
	}
	
	
	/**
	 * 把 Json String转化为对象
	 * @param <T>
	 * @param json_str    
	 * @param klass   对象类型， 例如 HashMap.class
	 * @return 转化的对象
	 * @see  如果把字符串转化为HashMap,类型为HashMap<String ,Object>
	 *       HashMap<String ,Object> hm = jsonString2Object(str_json,HashMap.class);
	 */
	public static <T> T jsonString2Object(String json_str, Class<T> klass) {       
		T object;       
		try { 	         
			object = JSON.parseObject(json_str, klass);         	       
		} catch (RuntimeException e) { throw e; } 
		  catch (Exception e) {     return null;     } 
	     
		return object;   
	} 	
	
	
	
	public static void main(String[] args) {
		
		HashMap<Integer, String> hm_kv = new HashMap<Integer, String>();
		hm_kv.put(1, "dog");
		hm_kv.put(2,"cat");
		hm_kv.put(3, "monkey");
		hm_kv.put(4, "donkey");		
		String s = object2JsonString(hm_kv);
		System.out.println(s);
		
		
		LinkedList list = new LinkedList();
		list.add("hello");
		list.add("world");
		list.add(hm_kv);	
		s = object2JsonString(list);
		System.out.println(s);		
		

		LinkedList lnk = jsonString2Object(s, LinkedList.class);
		System.out.println(lnk);	
	}

}
